<?php
/**
 * @description : The WebServiceServer Of Mstat.
 * @class-name : MstatWebServiceServer()
 * @author : stephen.mo <stephen.mo@achievo.com>
 * @date : 2010-04-02
 */

class MstatWebServiceServer {

    /**
     * @description : return the timestamp of you want to return.
     * @param int $year     .how many years will you return ?
     * @return int.
     * @author Stephen Mo
     */
    static public function defaultYearsTimestamp($year=3) {
        $result = 0;
        $one_day = 24*60*60;
        $now_year = date('Y');
        for($i=$year;$i>0;$i--) {
            $test_year = $now_year.'-01-01';
            $this_year = (date('L',strtotime($test_year))) ? 366 : 365;
	        $now_year--;
	        $result += $this_year*$one_day;
        }
	    return $result;
    }


    /**
     * @description : to return field value of database.
     * @param string $tbl       .table name.
     * @return array.
     * @author Stephen Mo
     */
    static private function getShowFieldsFromTable($tbl) {
        $result = array(
			            'video_access_log'=>array('programme_id','programme_name','episode_id','episode_title','video_id','video_title','play_time'),
			            'member_access_log'=>array('login_time','logout_time')
		  			);
	    return (isset($result[$tbl])) ? $result[$tbl] : array();
    }


    /**
     * @description : show the pages infos.
     * @param int $page         .the page number.
     * @param int $rows         .to show rows records of one page.
     * @param int $total        .all records number.
     * @param array $datas      .data source.
     * @return array
     * @author Stephen Mo
     */
    static public function getPageInfo($page,$rows,$total,$datas) {
        $result = array();
        $page = intval($page);
        if(!in_array($rows, array(10, 20, 30, 40 , 50))){
            $rows = MstatWebServiceServerConfig::WEB_SERVICE_SHOW_ROWS;
        }

        //all total pages.
        $total_page = ceil($total/$rows);
        $data = $datas['data'];
        
	    //current page.
        $page = ($page<1) ? 1 : (($page>$total_page) ? $total_page : $page);
        $start = 0;   //($page-1)*$rows;

        $rows = ($total<=$rows) ? $total : ($rows>count($data) ? count($data) : $rows);
	    $fields_list = self::getShowFieldsFromTable($datas['name']);

        //page info.
        $result['page'] = $page;
        //$result['total'] = $total_page;
        $result['limit'] = $rows;
        $temp_data = array();
        for ($i=$start;$i<$rows;$i++) {
             $temp_fields = array();
             foreach($fields_list as $key=>$value) {
                $temp_value = $data[$i]["$value"];
                $temp_fields["$value"] = $temp_value;
             }

            if ($datas['name']=='video_access_log') {
	            $time_of_day = date('Y-m-d',strtotime($data[$i]['play_time']));
                $temp_data[$time_of_day][] = $temp_fields;
	        }
            else {
		        $temp_data[] = $temp_fields;
	        }
            unset($temp_fields);
        }

        $result['rows'] = $temp_data;
        return $result;
    }

    // {{{ static public function getVideoViewRecord($member_id,$start_time=null,$end_time=null,$page=1,$limit=20,$order='DESC') {
    static public function getVideoPageViewRecord($member_id,$start_time=null,$end_time=null,$page=1,$limit=20,$order='DESC') {
            $data = array();
            $temp_val = array();
        $start_time = (empty($start_time)) ? time()-(self::defaultYearsTimestamp()) : $start_time;
        $end_time = (empty($end_time)) ? time() : $end_time;
                $page = (empty($page)) ? 1 : intval($page);
                $limit = (empty($limit)) ? 20 : intval($limit);
                $start = ($page-1) * $limit;

        //using cache.
            $datas = MstatOperationOfDatabase::getInstance()->getPageViewVideoRecord($member_id,$start_time,$end_time,$start,$limit,$order);
            $total = intval($datas['total']);
            $page_info = self::getPageInfo($page,$limit,$total,$datas);

        $data['login_id'] = $member_id;
        $data['start_time'] = date('Y-m-d H:i:s',$start_time);
        $data['end_time'] = date('Y-m-d H:i:s',$end_time);
        $data['current_page'] = $page_info['page'];
        $data['limit'] = $page_info['limit'];
        $data['total'] = $total;
        $data['records'] = $page_info['rows'];
        return $data;
    }
    // }}}


    /**
     * @description : get the member's view video records.
     * @param string $member_id	   .member's user id.
     * @param int $start_time      .time of start check. eg:1264370400
     * @param int $end_time        .time of end check.   eg:1264390400
     *                             --default : current time unix-timestamp
     * @param int $page            .begin show for you need to return page of record.
     *                             --default : 1
     * @param int $limit           .how many records will show of your page.
     *                             --default : 20
     * @param string $order        .sort --default 'DESC' 
     * @return array.
     * @author Stephen Mo
     *
     */
    static public function getVideoViewRecord($member_id,$start_time=null,$end_time=null,$page=1,$limit=20,$order='DESC') {
	    $data = array();
	    $temp_val = array();
        $start_time = (empty($start_time)) ? time()-(self::defaultYearsTimestamp()) : $start_time;
        $end_time = (empty($end_time)) ? time() : $end_time;
		$page = (empty($page)) ? 1 : intval($page);
		$limit = (empty($limit)) ? 20 : intval($limit);
		$start = ($page-1) * $limit;

        //using cache.
	    $datas = MstatOperationOfDatabase::getInstance()->getViewVideoRecord($member_id,$start_time,$end_time,$start,$limit,$order);
	    $total = intval($datas['total']);
	    $page_info = self::getPageInfo($page,$limit,$total,$datas);

        $data['login_id'] = $member_id;
        $data['start_time'] = date('Y-m-d H:i:s',$start_time);
        $data['end_time'] = date('Y-m-d H:i:s',$end_time);
        $data['current_page'] = $page_info['page'];
        $data['limit'] = $page_info['limit'];
        $data['total'] = $total;
        $data['records'] = $page_info['rows'];
        return $data;	
    }


    /**
     * @description : get the member's sign-in & sign-out records.
     * @param string $member_id    .member's user id.
     * @param int $start_time      .time of start check. eg:1264370400.
     * @param int $end_time        .time of end check.   eg:1264390400.
     *                             --default :current time().unix-timestamp
     * @param int $page            .begin show for you need to return page of record.
     *                             --default :1
     * @param int $limit           .how many records will show of your page.
     *                             --default :20
     * @param string $order        .sort default 'desc'
     * @return array().
     * @author Stephen Mo
     */
    static public function getSignInHistory($member_id,$start_time=null,$end_time=null,$page=1,$limit=20,$order='DESC') {
		$data = array();
        $start_time = (empty($start_time)) ? time()-(self::defaultYearsTimestamp()) : $start_time;
	    $end_time = (empty($end_time)) ? time() : $end_time;
		$page = (empty($page)) ? 1 : intval($page);
		$limit = (empty($limit)) ? 20 : intval($limit);
		$start = ($page-1) * $limit;

		//using cache.
		$datas = MstatOperationOfDatabase::getInstance()->getSignInOutRecord($member_id,$start_time,$end_time,$start,$limit,$order);
		$total = intval($datas['total']);
		$page_info = self::getPageInfo($page,$limit,$total,$datas);
		
		$data['login_id'] = $member_id;
		$data['start_time'] = date('Y-m-d H:i:s',$start_time);
		$data['end_time'] = date('Y-m-d H:i:s',$end_time);
		$data['current_page'] = $page_info['page'];
		$data['limit'] = $page_info['limit'];
        $data['total'] = $total;
		$data['records'] = $page_info['rows'];
		return $data;
    }

    
    /**
     * @description : count the video's views.
     * @param int $video_id     .count views by video_id.
     * @return array
     * @author stephen mo
     */
    static public function video($video_id) {
        if (empty($video_id) || intval($video_id)==0) return -1;
        $data = MstatOperationOfDatabase::getInstance()->getVideoViewCount($video_id);
        return $data;
    }


    /**
     * @description : get the programme's views.
     * @param int $programme_id         .the programme's id.
     * @return array
     * @author Stephen Mo
     */
    static public function programme($programme_id) {
        if (empty($programme_id) || intval($programme_id)==0) return -1;
	    //using cache.
	    $datas = MstatOperationOfDatabase::getInstance()->getProgrammeViewCount($programme_id);
	    return $datas;
    }


    /**
     * @description : get the video's views.
     * @param int $video_id         .the video's id.
     * @param string $category      .the category name. default 'ALL' ,other format is 'AAA,BBB,CCC'
     * @param int $offset           .the current page.  default 0.
     * @param int $limit            .the limit number.  default 0.
     * @param string $sort          .the sort value.    default 'online_time',other is 'view' or 'favour'.
     * @param string $start_date    .begin date.
     * @param string $end_date      .end date.
     * @param array $lang           .language.
     * @return array
     * @author Stephen Mo
     */
    static public function contentVideos($video_id=null,$category='ALL',$sort='online_time',$start_date=null,$end_date=null,$offset=1,$limit=10,$lang=null) {
        $result = array();
        $condition = '';
        if (empty($video_id)) {
            if (strtoupper($category)!='ALL') {
                $categorys = explode(',',$category);
                //maybe an array. eg:(drama,music,fresh...)
                if (count($categorys)>1) {
                    $condition .= ' AND category_path IN ("'.implode('","',$categorys).'") ';
                }
                else {
                    //it's a string.
                    $condition .= ' AND category_path="'.$category.'" ';
                }
            }
            
            if (empty($sort)) return -1;
            if ($sort != 'online_time') {
                if (empty($start_date) && empty($end_date)) return -1;
                if (strtotime($end_date) <= strtotime($start_date)) return -1;
                $condition .= ' AND (UNIX_TIMESTAMP(access_datetime)>'.strtotime($start_date).' AND UNIX_TIMESTAMP(access_datetime)<'.strtotime($end_date).') ';
            }

            if (!empty($lang)) $condition .= ' AND video_lang="'.$lang.'" ';
        }
        else {
            if (empty($video_id) || intval($video_id)==0) return -1;
            $condition .= ' AND video_id='.$video_id;
        }

        $data = MstatOperationOfDatabase::getInstance()->getVideosViewCount($condition,$sort,$offset,$limit);        
        //using cache.
        $result['total'] = $data['total'];
        $result['size'] = 1;
        $result['category'] = $category;
        $result['offset'] = $offset;
        $result['limit'] = $limit;
        $result['sort'] = $sort;
        $result['start_date'] = $start_date;
        $result['end_date'] = $end_date;
        $result['data'] = $data['records'];
      
        return $result;
    }


    /**
     * @description : get the programme's views.
     * @param int $programme_id     .the programme's id.
     * @param string $category      .the category name. default 'ALL' ,other format is 'AAA,BBB,CCC'
     * @param int $offset           .the current page.  default 0.
     * @param int $limit            .the limit number.  default 0.
     * @param string $sort          .the sort value.    default 'online_time',other is 'view' or 'favour'.
     * @param string $start_date    .begin date.
     * @param string $end_date      .end date.
     * @param array $lang           .language.
     * @return array
     * @author Stephen Mo
     */
    static public function contentProgrammes($programme_id=null,$category='ALL',$sort='online_time',$start_date=null,$end_date=null,$offset=1,$limit=10,$lang=null) {
        $result = array();
        $condition = '';
        if (empty($video_id)) {
            if (strtoupper($category)!='ALL') {
                $categorys = explode(',',$category);
                //maybe an array. eg:(drama,music,fresh...)
                if (count($categorys)>1) {
                    $condition .= ' AND category_path IN ("'.implode('","',$categorys).'") ';
                }
                else {
                    //it's a string.
                    $condition .= ' AND category_path="'.$category.'" ';
                }
            }
            
            if (empty($sort)) return -1;
            if ($sort != 'online_time') {
                if (empty($start_date) && empty($end_date)) return -1;
                if (strtotime($end_date) <= strtotime($start_date)) return -1;
                $condition .= ' AND (UNIX_TIMESTAMP(access_datetime)>'.strtotime($start_date).' AND UNIX_TIMESTAMP(access_datetime)<'.strtotime($end_date).') ';
            }

            if (!empty($lang)) $condition .= ' AND video_lang="'.$lang.'" ';
        }
        else {
            if (empty($programme_id) || intval($programme_id)==0) return -1;
            $condition .= ' AND programme_id='.$programme_id;
        }

        $data = MstatOperationOfDatabase::getInstance()->getProgrammesViewCount($condition,$sort,$offset,$limit);        
        //using cache.
        $result['total'] = $data['total'];
        $result['size'] = 1;
        $result['category'] = $category;
        $result['offset'] = $offset;
        $result['limit'] = $limit;
        $result['sort'] = $sort;
        $result['start_date'] = $start_date;
        $result['end_date'] = $end_date;
        $result['data'] = $data['records'];
        return $result;
    }
    
    
    /**
     * @description : get the five minutes before datas.
     * @param int $type : the return data's type. eg:1=video,2=programme
     * @param int $time : the time of interval,the unit is 'minute'
     * @return mixed
     * @author : stephen
     */
    static public function getVideoStats($type=1,$time=5,$order=array()) {
        $result = array();
        $current_time = time();
        $time_of_interval = $time*60;//unit is second.
        $real_time_text = date('Y-m-d H:i:s',$current_time-$time_of_interval);
        $current_time_text = date('Y-m-d H:i:s',$current_time);
        $result = MstatOperationOfDatabase::getInstance()->getVideoStatsByTypeAndInterval($type,$real_time_text,$current_time_text,$order);
        //using cache.
        return $result;
    }

    /**
     * @descrtiption : get the viewing and favour counts for fp_video_access.
     * @param int $type : the return data's type.eg:1=video,2=programme.
     * @param array $video_ids : the search video ids.
     * @param array $category_ids : the search category ids.
     * @param int $period : the Time Bucket.only (5,10,15,20).
     * @param int $offset : start records number.
     * @param int $limit : how many records return.
     * @param array $order : the sort array.eg:array('view'=>'asc','favour'=>'desc');
     */
    static public function getVideoStatsByPeriod($type,$video_ids=null,$category_ids=null,$period=5,$offset=0,$limit=10,$order=array('view'=>'desc')) {
        $time_bucket = MstatWebServiceServerConfig::$time_bucket_list;
        $time_bucket_keys = array_keys($time_bucket);
        if (empty($period) || !in_array($period,$time_bucket_keys)) {
            $period = 5;
        }
        
        $offset = (empty($offset)) ? 0 : $offset;
        $limit = (empty($limit)) ? 10 : $limit;
        $order = (empty($order)) ? array('view'=>'desc') : $order;
        $video_ids = (empty($video_ids)) ? array() : $video_ids;
        $category_ids = (empty($category_id)) ? array() : $category_ids;

        $result = MstatOperationOfDatabase::getInstance()->getVideoViewingFavourStat($time_bucket,$type,$video_ids,$category_ids,$period,$offset,$limit,$order);
        $data['offset'] = ($offset>$result['total']) ? $result['total'] : $offset;
        $data['limit'] = $limit;
        $data['total'] = $result['total'];

        $tmp_records = array();
        if (!empty($result['records'])) {
            foreach($result['records'] as $key=>$val) {
                $key_id = $val['field_id'];
                $views = intval($val['view']);
                $favours = intval($val['favour']);
                if (!isset($tmp_records[$key_id])) $tmp_records[$key_id] = array();
                if (!isset($tmp_records[$key_id]['view'])) $tmp_records[$key_id]['view'] = 0;
                if (!isset($tmp_records[$key_id]['view'])) $tmp_records[$key_id]['view'] = 0;
                $tmp_records[$key_id]['view'] += $views;
                $tmp_records[$key_id]['favour'] += $favours;
            }
        }
        $data['records'] = $tmp_records;
        return $data;
    }

}

?>

